#include "PostProcessEffect.h"

#include "App/Window.h"
#include "Render/ColorRenderPass.h"

PostProcessEffect::PostProcessEffect(const Ref<Shader> &shader, bool enabled)
    : m_shader(shader), m_enabled(enabled)
{
}

void PostProcessEffect::Render()
{
  if (!m_enabled)
    return;

  auto &window = Window::GetInstance();
  int32_t width = window.GetWidth();
  int32_t height = window.GetHeight();
  if (m_frameBuffer == nullptr || m_frameBuffer->GetWidth() != width || m_frameBuffer->GetHeight() != height)
    m_frameBuffer = CreateRef<FrameBuffer>(width, height, false, 1);

  Ref<FrameBufferStack> frameBufferStack = window.GetFrameBufferStack();
  Ref<FrameBuffer> colorSource = frameBufferStack->Peek();
  frameBufferStack->Push(m_frameBuffer); // 5

  Update();
  ColorRenderPass::RenderTextureWithEffect(colorSource->GetColorAttachment(0), m_shader);

  Ref<FrameBuffer> result = frameBufferStack->Pop();
  ColorRenderPass::RenderTexture(result->GetColorAttachment(0));
}